import { createRouter, createWebHashHistory} from '@ionic/vue-router';
import { RouteRecordRaw } from 'vue-router';
import TabsPage from '../views/TabsPage.vue'
import axios from 'axios';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/LoginPage.vue')
  },
  {
    path: '/logs',
    name: 'Logs',
    component: () => import('@/views/LogsList.vue')
  },
  {
    path: '/popupwindow/:triggerName',
    name:'popupwindow',
    component: () =>import('@/views/PopupWindow.vue')
  },
  {
    path: '/systempopup',
    name:'systempopup',
    component: () =>import('@/views/SystemPopup.vue')
  },
  {
    path: '/eventdetails/:triggerName',
    name:'eventdetails',
    component: () => import('@/views/EventDetails.vue'),
    props: true
  },
  {
    path: '/contentpage/:id',
    name:'contentpage',
    component: () =>import('@/views/ContentPage.vue'),
    props: true
  },
  {
    path: '/validatepage/:triggerName/:eventName?/:svomBurstId?/:triggerId?',
    name:'validatepage',
    component: () => import('@/views/ValidatePage.vue'),
    props: (route) => ({
      triggerName: route.params.triggerName,
      eventName: route.params.eventName || '',
      svomBurstId: route.params.svomBurstId || '',
      triggerId: route.params.triggerId || '' 
    })
  },
  {
    path: '/tabs/',
    component: TabsPage,
    children: [
      {
        path: '',
        redirect: '/tabs/eventlist'
      },
      {
        path: 'eventlist',
        name: 'eventlist',
        component: () => import('@/views/EventList.vue'),
      },
      {
        path: 'dutypage',
        component: () => import('@/views/DutyPage.vue')
      },
      {
        path: 'minepage',
        component: () => import('@/views/MinePage.vue')
      },
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫部分
router.beforeEach(async (to, from, next) => {
  const publicPages = ['/login'];
  const authRequired = !publicPages.includes(to.path);
  const accessToken = localStorage.getItem('accessToken');
  
  // 处理根路径重定向
  if (to.path === '/') {
    if (accessToken) {
      next('/tabs/eventlist');
      return;
    } else {
      next('/login');
      return;
    }
  }
  
  if (authRequired) {
    if (!accessToken) {
      console.log('No token, redirect to login');
      // 保存目标路径以便登录后跳转
      localStorage.setItem('redirectPath', to.fullPath);
      next('/login');
      return;
    }

    try {
      const response = await axios.get('https://www.svom-gwacn.cn/svomUPMS/user/profile', {
        params: {
          accessToken: accessToken
        },
        headers: { Authorization: `Bearer ${accessToken}` }, 
      });
      const userData = response.data.data;
      localStorage.setItem('userInfo', JSON.stringify(userData.userInfo));
      localStorage.setItem('roleInfo', JSON.stringify(userData.userRole));
      localStorage.setItem('userId', response.data.data.userInfo.userId);
      localStorage.setItem('roleIds', response.data.data.userRole.roleIds);
      localStorage.setItem('name', response.data.data.userInfo.name);
      localStorage.setItem('phone', response.data.data.userInfo.phone);
      console.log('用户信息验证成功:', response.data); 
      localStorage.setItem('lastActiveTime', Date.now().toString()); 
      next();
      
      const response1 = await axios.get('https://www.svom-gwacn.cn/svomUPMS/role/all', {
        headers: { Authorization: `Bearer ${accessToken}` }, 
      });
      localStorage.setItem('roleId', response1.data.data[3].roleId);
      localStorage.setItem('roleName', response1.data.data[3].roleName); 
      localStorage.setItem('displayRoleName', response1.data.data[3].displayRoleName);
    } catch (error) {
      console.error('Token验证失败:', error);
      localStorage.removeItem('accessToken');
      localStorage.removeItem('userId');
      localStorage.removeItem('roleIds');
      localStorage.removeItem('roleInfo');
      localStorage.removeItem('roleId');
      localStorage.removeItem('roleName');
      localStorage.removeItem('name');
      localStorage.removeItem('phone');
      localStorage.removeItem('userRole');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('displayRoleName');
      // 保存目标路径以便登录后跳转
      localStorage.setItem('redirectPath', to.fullPath);
      next('/login');
    }
  } else {
    next();
  }
});

export default router